import sqlite3
from datetime import datetime
from typing import List, Type, Optional, Dict
from peewee import Model, AutoField, CharField, TextField, DateTimeField, DoesNotExist

from common.utils.utils_log import AntLogger
from plugins.ant_das.base_dao import BaseDao
from plugins.ant_das.database_pool import get_database_pool


class SettingModel(Model):
    """系统设置模型"""
    id = AutoField()
    setting_key = CharField(unique=True)
    setting_value = TextField(null=True)
    setting_desc = CharField(null=True)
    created_at = DateTimeField(default=datetime.now)
    updated_at = DateTimeField(default=datetime.now)

    class Meta:
        database = get_database_pool().database
        table_name = "ant_system_setting"

    def __repr__(self):
        return f"Setting(key='{self.setting_key}', desc='{self.setting_desc}')"


class SettingDas(BaseDao):
    """系统设置数据访问对象"""
    
    @property
    def model_class(self) -> Type[SettingModel]:
        return SettingModel
    
    def insert_data(self, model_instance: SettingModel) -> int:
        """
        插入新的系统设置
        :param model_instance: 系统设置模型实例
        :return: 新插入记录的ID
        """
        try:
            model_instance.save()
            AntLogger.info(f"设置数据插入成功，ID: {model_instance.id}")
            return model_instance.id
        except Exception as e:
            AntLogger.error(f"插入设置数据失败: {e}")
            raise

    def update_data(self, model_instance: SettingModel) -> bool:
        """
        更新系统设置
        :param model_instance: 系统设置模型实例
        :return: 是否更新成功
        """
        try:
            model_instance.updated_at = datetime.now()
            rows_affected = model_instance.save()
            AntLogger.info(f"设置数据更新成功，影响行数: {rows_affected}")
            return rows_affected > 0
        except Exception as e:
            AntLogger.error(f"更新设置数据失败: {e}")
            raise

    def delete_by_id(self, record_id: int) -> bool:
        """
        根据ID删除系统设置
        :param record_id: 设置ID
        :return: 是否删除成功
        """
        try:
            query = self.model_class.delete().where(self.model_class.id == record_id)
            rows_affected = query.execute()
            AntLogger.info(f"设置数据删除成功，影响行数: {rows_affected}")
            return rows_affected > 0
        except Exception as e:
            AntLogger.error(f"删除设置数据失败: {e}")
            raise
    
    def get_setting_by_key(self, key: str) -> Optional[SettingModel]:
        """
        根据键获取设置
        :param key: 设置键
        :return: 设置模型实例或None
        """
        return self.query_one_by_field("setting_key", key)
    
    def get_all_settings(self) -> List[SettingModel]:
        """
        获取所有设置
        :return: 设置列表
        """
        return self.query()
    
    def save_or_update_setting(self, key: str, value: str, desc: str = None) -> SettingModel:
        """
        保存或更新设置
        :param key: 设置键
        :param value: 设置值
        :param desc: 设置描述
        :return: 设置模型实例
        """
        setting = self.get_setting_by_key(key)
        
        if setting:
            # 更新现有设置
            setting.setting_value = value
            if desc:
                setting.setting_desc = desc
            setting.updated_at = datetime.now()
            self.update_data(setting)
        else:
            # 创建新设置
            setting = SettingModel(
                setting_key=key,
                setting_value=value,
                setting_desc=desc,
                created_at=datetime.now(),
                updated_at=datetime.now()
            )
            self.insert_data(setting)
        
        return setting
    
    def delete_setting_by_key(self, key: str) -> bool:
        """
        根据键删除设置
        :param key: 设置键
        :return: 是否删除成功
        """
        setting = self.get_setting_by_key(key)
        if setting:
            return self.delete_by_id(setting.id)
        return False 